<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable
          @keyup.enter.native="getList" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" size="mini" @click="getList">搜索
        </el-button>
        <el-button type="success" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="newlyAdded">新增
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="brandList" border>

      <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="logo" align="center" prop="logo" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-image style="width:100px;height:50px" :src="scope.row.logo"
            :preview-src-list="scope.row.srcList">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enable" @change="handleStatusChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="商品数量" align="center" prop="skuNum" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="排序" align="center" prop="orderNum" :show-overflow-tooltip="true">
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="modify(scope.row)"> 修改 </el-button>
          <el-button size="mini" @click="imports(scope.row)"> 导入商品 </el-button>
          <el-button size="mini" @click="see(scope.row)"> 查看商品 </el-button>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 新增  修改-->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入品牌名称" style="width:80%" />
        </el-form-item>
        <el-form-item label="logo" prop="logo">
          <div v-if="title==='新增'">
            <input id="files" type="file" @change="requiredChange" v-if="logoStatus">
            <img class="detailAppImage" :src="form.logo" v-if="!logoStatus">
            <span @click="deletePicture" v-if="!logoStatus">删除</span>
          </div>
          <div v-if="title==='修改'">
            <input id="files" type="file" @change="requiredChange" v-if="!logoStatus">
            <img class="detailAppImage" :src="form.logo" v-if="logoStatus">
            <el-button size="mini" style="margin-left:50px" @click="deletePicture"
              v-if="logoStatus"> 删除图片 </el-button>
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input v-model="form.orderNum" style="width:30%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入 -->
    <el-dialog title="上传" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="r+'/goods/brand/'+id+'/importSku?updateSupport=0'" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false"
        drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text"> 将文件拖到此处，或 <em>点击上传</em> </div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false"
            style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看商品 -->
    <el-dialog title="查看商品" :visible.sync="goodsOpen">
      <el-table v-loading="goodsLoading" :data="goodsList">
        <el-table-column label="商品名称" align="center" prop="goodsName" width="200"
          :show-overflow-tooltip="true" />
        <el-table-column label="编码" align="center" prop="identifier" width="100"
          :show-overflow-tooltip="true" />
        <el-table-column label="规格" align="center" prop="simpleSpecs" width="100"
          :show-overflow-tooltip="true" />
        <el-table-column label="生产厂家" align="center" prop="manufacturer"
          :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" @click="deleteGoods(scope.row)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="goodsTotal>0" :total="goodsTotal" :page.sync="goodsParams.pageNum"
        :limit.sync="goodsParams.pageSize" @pagination="getGoodsList" />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="goodsOpen=false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getBrandList, setBrand, updateBrand, updateBrandStatus, uploadBrandGoods, deleteBrandGoods } from '@/api/goods/brand.js'
import { listGoodsSku } from '@/api/goods/goods.js'
import { uploadPicture } from "@/api/promotion/seckill"
import { getToken } from "@/utils/auth"

export default {
  name: "Brand",
  data () {
    return {
      r: process.env.VUE_APP_BASE_API,
      loading: true,
      goodsLoading: true,
      brandList: [],
      goodsList: [],
      currentRow: '',
      total: 0,
      goodsTotal: 0,
      queryParams: { pageNum: 1, pageSize: 10 },
      goodsParams: { pageNum: 1, pageSize: 10 },
      title: '新增',
      open: false,
      goodsOpen: false,
      form: {},
      id: '',
      upload: { open: false, isUploading: false, headers: { Authorization: "Bearer " + getToken() } },
      logoStatus: true,
    }
  },
  created () { this.getList() },
  methods: {
    // 删除行商品
    deleteGoods (row) {
      let that = this
      this.$modal.confirm('确认删除吗？').then(function () {
        return deleteBrandGoods(that.id, row.id)
      }).then(() => {
        this.$modal.msgSuccess("成功")
        this.getGoodsList()
        this.getList()
      })
    },
    // 查看品牌商品
    see (row) {
      this.goodsOpen = true
      this.id = row.id
      this.goodsParams.brandId = row.id
      this.getGoodsList()
    },
    // 品牌商品
    getGoodsList () {
      this.goodsLoading = true
      listGoodsSku(0, this.goodsParams).then(res => {
        this.goodsList = res.rows
        this.goodsTotal = res.total
        this.goodsLoading = false
      })
    },
    // 新增
    newlyAdded () {
      this.title = '新增'
      this.open = true
      this.logoStatus = true
      this.form = {}
    },
    // 修改
    modify (row) {
      this.title = '修改'
      this.open = true
      this.logoStatus = true
      this.form = row
      this.id = row.id
    },
    // 导入商品
    imports (row) {
      this.id = row.id
      this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true }
      )
      this.getList()
    },
    /** 下载模板操作 */
    importTemplate () {
      this.download(
        "goods/brand/goods/importTemplate", {},
        `导入品牌商品模板_${this.parseTime(new Date().getTime(), "{y}-{m}-{d}_{h}{i}{s}")}.xlsx`
      )
    },
    // 提交上传文件
    submitFileForm () { this.$refs.upload.submit() },


    // 文件选择框
    requiredChange (e) {
      let formdata = new FormData()
      formdata.append("file", e.target.files[0])
      uploadPicture(formdata).then(res => {
        if (res.code === 200) {
          this.form.logo = res.data.url
          this.form.imageId = res.data.id
          this.logoStatus = false
        }
      })
    },
    // 删除图片
    deletePicture () {
      this.form.logo = ''
      this.logoStatus = false
    },
    // 新增确认
    submitForm () {
      let that = this
      if (this.title === '新增') {
        this.$modal.confirm('确认新增吗？').then(function () {
          return setBrand(that.form)
        }).then(() => {
          this.open = false
          this.getList()
          this.$modal.msgSuccess("成功")
        })
      }
      if (this.title === '修改') {
        this.$modal.confirm('确认修改吗？').then(function () {
          return updateBrand(that.id, that.form)
        }).then(() => {
          this.open = false
          this.getList()
          this.$modal.msgSuccess("成功")
        })
      }
    },
    // 重置
    resetQuery () {
      this.queryParams = { pageNum: 1, pageSize: 10, }
      this.getList()
    },
    /** 查询列表 */
    getList () {
      this.loading = true;
      getBrandList(this.queryParams).then(res => {
        if (res.code === 200) {
          res.rows.forEach(i => this.$set(i, 'srcList', [i.logo]))
          this.brandList = res.rows
          this.total = res.total
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 状态修改
    handleStatusChange (row) {
      let text = row.enable ? "启用" : "禁用"
      this.$modal.confirm('确认' + text + '吗？').then(function () {
        return updateBrandStatus(row.id, { enable: row.enable })
      }).then(() => {
        this.$modal.msgSuccess(text + "成功")
      }).catch(() => {
        row.enable = row.enable ? false : true
      })
    },

  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  top: 20px;
  img {
    width: 200px;
    height: 200px;
  }
}
</style>
